// 引入配置文件
import baseConfig from '@/config/config.base'
import md5 from "@/utils/md5"
let jwdSignKey = ""
let appId = "";
if (baseConfig.environment == "dev") {
  jwdSignKey = "bac0754623212"
  appId = "1007"
}
if (baseConfig.environment == "test") {
  jwdSignKey = "bac0754623212"
  appId = "1007"
}
if (baseConfig.environment == "prod") {
  jwdSignKey = "f06fda4a54464c85a226ff31663073e7"
  appId = "1007"
}
// 签名
function creatSign(data) {
	// const jwdSignKey = "bac0754623212";
	let tempMap = new Map();
	// for (let key in data) {
	// 	tempMap.set(key, data[key]);
	// }
	for (let [key, val] of Object.entries(data)) {
		if(isObeject(val) || isArray(val)){
			tempMap.set(key, JSON.stringify(data[key]));
		}else{
			tempMap.set(key, data[key]);
		}
	}

	let arrayObj = Array.from(tempMap);
	arrayObj.sort(function(a, b) {
		return a[0].localeCompare(b[0])
	});
	var sortedMap = new Map(arrayObj);
	let signNoMd5 = "";
	for (let [key, val] of sortedMap.entries()) {
		if ((val !== null) && (key !== "sign") && (key !== "key")) {
			signNoMd5 += (key + "=" + val + "&");
		}
	}
	signNoMd5 += ("key=" + jwdSignKey);
	console.log("加密参数 = " + signNoMd5);
	let signedString = md5(signNoMd5);
	console.log("加密结束的参数 = " + signedString);
	return signedString;
}

// 补全请求数据
 function getAllData(data) {
	const timeStamp = Date.now().toString();
	let reqData = {
		appId,
		timeStamp,
		...data
	};
	console.log("reqData=",reqData);
	return reqData;
}


// 去除对象里的
function isArray(value) {
	return Object.prototype.toString.call(value) === '[object Array]'
}

function isObeject(value) {
	return Object.prototype.toString.call(value) === '[object Object]'
}

function removeDataEmpty(obj) {
	// 是否是数组
	if (isArray(obj)) {
		obj.forEach((elem, i) => {
			if ((elem === null) || (isObeject(elem) && !Object.keys(obj).length)) {
				obj.splice(i, 1)
				return
			}
			removeDataEmpty(elem)
		})
		return
	}
	// 是否是对象
	if (isObeject(obj) && Object.keys(obj).length) {
		Object.keys(obj).forEach((key) => {
			if (obj[key] === null) {
				delete obj[key]
				return
			}
			removeDataEmpty(obj[key])
		})
	}
	return obj
}

function deepCopy(obj) {
		let result = Array.isArray(obj) ? [] : obj === null ? null : {};
		for (let key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (typeof obj[key] === 'object') {
					result[key] = deepCopy(obj[key]);
				} else {
					result[key] = obj[key];
				}
			}
		}
		return result;
	}
// 加工请求数据
export function getReqData(orign_data) {
	console.log("orign_data=",orign_data);
	let oldData = deepCopy(orign_data);
	//去掉value为null的key和值
	let data = removeDataEmpty(oldData)
	let allData = getAllData(data);
	let signedString = creatSign(allData);
	// allData.set("key",signedString);
	let sign = signedString;
	let reqAllData = {
		...allData,
		sign
	};
	return reqAllData;
}
